package com.hulk.dryad.persistence.service.impl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hulk.dryad.common.constant.CacheConstants;
import com.hulk.dryad.common.constant.CommonConstants;
import com.hulk.dryad.common.util.BCryptPasswordEncoderUtil;
import com.hulk.dryad.persistence.entity.*;
import com.hulk.dryad.persistence.injector.datascope.DataScope;
import com.hulk.dryad.persistence.mapper.SysUserMapper;
import com.hulk.dryad.persistence.service.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author kim
 * @date 2017/10/31
 */
@DS("#" + CommonConstants.TENANT_ID)
@Slf4j
@Service
@AllArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserModel> implements SysUserService {

	private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

	private final SysMenuService sysMenuService;

	private final SysRoleService sysRoleService;

	private final SysDeptService sysDeptService;

	private final SysUserRoleService sysUserRoleService;

	private final SysDeptRelationService sysDeptRelationService;

	/**
	 * 保存用户信息
	 * @param userDto DTO 对象
	 * @return success/fail
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean saveUser(UserExtModel userDto) {
		SysUserModel sysUser = new SysUserModel();
		BeanUtils.copyProperties(userDto, sysUser);
		sysUser.setDelFlag(CommonConstants.STATUS_NORMAL);
		sysUser.setPassword(ENCODER.encode(userDto.getPassword()));
		baseMapper.insert(sysUser);
		List<SysUserRoleModel> userRoleList = userDto.getRole().stream().map(roleId -> {
			SysUserRoleModel userRole = new SysUserRoleModel();
			userRole.setUserId(sysUser.getUserId());
			userRole.setRoleId(roleId);
			return userRole;
		}).collect(Collectors.toList());
		return sysUserRoleService.saveBatch(userRoleList);
	}

	/**
	 * 通过查用户的全部信息
	 * @param sysUser 用户
	 * @return
	 */
	@Override
	public UserInfoModel findUserInfo(SysUserModel sysUser) {
		UserInfoModel userInfoModel = new UserInfoModel();
		userInfoModel.setSysUserModel(sysUser);
//		// 设置角色列表 （ID）
//		List<Integer> roleIds = sysRoleService.findRolesByUserId(sysUser.getUserId()).stream().map(SysRoleModel::getRoleId)
//				.collect(Collectors.toList());
//		userInfoModel.setRoles(ArrayUtil.toArray(roleIds, Integer.class));

		List<SysRoleModel> userRoles = sysRoleService.findRolesByUserId(sysUser.getUserId());
		// 设置角色列表 （ID）
		List<Integer> roleIds = userRoles.stream().map(SysRoleModel::getRoleId).collect(Collectors.toList());
		userInfoModel.setRoles(ArrayUtil.toArray(roleIds, Integer.class));
		// 设置角色名称列表
		List<String> roleCodes = userRoles.stream().map(SysRoleModel::getRoleCode).collect(Collectors.toList());
		userInfoModel.setRoleCodes(ArrayUtil.toArray(roleCodes, String.class));

		// 设置权限列表（menu.permission）
		Set<String> permissions = new HashSet<>();
		roleIds.forEach(roleId -> {
			List<String> permissionList = sysMenuService.findMenuByRoleId(roleId).stream()
					.filter(menu -> StringUtils.isNotEmpty(menu.getPermission())).map(MenuModel::getPermission)
					.collect(Collectors.toList());
			permissions.addAll(permissionList);
		});
		userInfoModel.setPermissions(ArrayUtil.toArray(permissions, String.class));
		return userInfoModel;
	}

	/**
	 * 分页查询用户信息（含有角色信息）
	 * @param page 分页对象
	 * @param userDTO 参数列表
	 * @return
	 */
	@Override
	public IPage getUsersWithRolePage(Page page, UserExtModel userDTO) {
		return baseMapper.getUserVosPage(page, userDTO, new DataScope());
	}

	/**
	 * 通过ID查询用户信息
	 * @param id 用户ID
	 * @return 用户信息
	 */
	@Override
	public UserModel selectUserVoById(Integer id) {
		return baseMapper.getUserVoById(id);
	}

	/**
	 * 删除用户
	 * @param sysUser 用户
	 * @return Boolean
	 */
	@Override
	@CacheEvict(value = CacheConstants.USER_DETAILS, key = "#sysUser.username")
	public Boolean deleteUserById(SysUserModel sysUser) {
		sysUserRoleService.deleteByUserId(sysUser.getUserId());
		this.removeById(sysUser.getUserId());
		return Boolean.TRUE;
	}

	@Override
	@CacheEvict(value = CacheConstants.USER_DETAILS, key = "#userExtModel.username")
	public Boolean updateUserInfo(UserExtModel userExtModel) {
		UserModel userModel = baseMapper.getUserVoByUsername(userExtModel.getUsername());
		if (!ENCODER.matches(userExtModel.getPassword(), userModel.getPassword())) {
			log.info("原密码错误，修改个人信息失败:{}", userExtModel.getUsername());
			return Boolean.FALSE;
		}

		SysUserModel sysUser = new SysUserModel();
		if (StrUtil.isNotBlank(userExtModel.getNewpassword1())) {
			sysUser.setPassword(ENCODER.encode(userExtModel.getNewpassword1()));
		}
		sysUser.setPhone(userExtModel.getPhone());
		sysUser.setUserId(userModel.getUserId());
		sysUser.setAvatar(userExtModel.getAvatar());
		return this.updateById(sysUser);
	}

	@Override
	@CacheEvict(value = CacheConstants.USER_DETAILS, key = "#userDto.username")
	public Boolean updateUser(UserExtModel userDto) {
		SysUserModel sysUser = new SysUserModel();
		BeanUtils.copyProperties(userDto, sysUser);
		sysUser.setUpdatedTime(LocalDateTime.now());

		if (StrUtil.isNotBlank(userDto.getPassword())) {
			sysUser.setPassword(BCryptPasswordEncoderUtil.encode(userDto.getPassword()));
		}
		this.updateById(sysUser);

		sysUserRoleService
				.remove(Wrappers.<SysUserRoleModel>update().lambda().eq(SysUserRoleModel::getUserId, userDto.getUserId()));
		userDto.getRole().forEach(roleId -> {
			SysUserRoleModel userRole = new SysUserRoleModel();
			userRole.setUserId(sysUser.getUserId());
			userRole.setRoleId(roleId);
			userRole.insert();
		});
		return Boolean.TRUE;
	}

	/**
	 * 查询上级部门的用户信息
	 * @param username 用户名
	 * @return R
	 */
	@Override
	public List<SysUserModel> listAncestorUsers(String username) {
		SysUserModel sysUser = this.getOne(Wrappers.<SysUserModel>query().lambda().eq(SysUserModel::getUsername, username));

		SysDeptModel sysDeptModel = sysDeptService.getById(sysUser.getDeptId());
		if (sysDeptModel == null) {
			return null;
		}

		Integer parentId = sysDeptModel.getParentId();
		return this.list(Wrappers.<SysUserModel>query().lambda().eq(SysUserModel::getDeptId, parentId));
	}

	/**
	 * 获取当前用户的子部门信息
	 * @return 子部门列表
	 */
	private List<Integer> getChildDepts(Integer deptId) {
		/** 获取当前部门的子部门*/
		return sysDeptRelationService
				.list(Wrappers.<SysDeptRelationModel>query().lambda().eq(SysDeptRelationModel::getAncestor, deptId)).stream()
				.map(SysDeptRelationModel::getDescendant).collect(Collectors.toList());
	}

	@Override
	public SysUserModel getOneByName(String username) {
		LambdaQueryWrapper<SysUserModel> qw = Wrappers.<SysUserModel>lambdaQuery()
				.eq(SysUserModel::getUsername, username);
		return this.getOne(qw);
	}

}
